use base64::Engine;
use nanoid::nanoid;
use serde::Deserialize;

use crate::models::models::components::v2ray::server::{ComponentV2rayServer, ComponentV2rayServerNetwork};
use crate::runtime::error::MagicBoxError;
use crate::runtime::response::Code;
use crate::runtime::result::MagicBoxResult;
use crate::utils::request;

/// 拉取服务器列表
pub(crate) async fn fetch_servers(url: &str) -> MagicBoxResult<Vec<ComponentV2rayServer>> {
    let response = request::http_get_bytes(url, None).await?;

    let links = base64::prelude::BASE64_STANDARD_NO_PAD.decode(response);
    if links.is_err() {
        let err = links.err().unwrap().to_string();
        log::error!("解析服务器列表失败: {}", err.as_str());

        return Err(MagicBoxError::new(Code::UndefinedError, err.as_str()));
    }

    let links = String::from_utf8(links.unwrap());
    if links.is_err() {
        let err = links.err().unwrap().to_string();
        log::error!("解析服务器列表失败，无效的响应内容: {}", err.as_str());

        return Err(MagicBoxError::new(Code::UndefinedError, err.as_str()));
    }

    let links = links.unwrap();
    let links = links.split("\n");

    let mut servers = Vec::new();
    for link in links {
        let server = parse_vmess_link(link);
        if server.is_some() {
            servers.push(server.unwrap());
        }
    }

    Ok(servers)
}

#[derive(Debug, Default, Clone, Deserialize)]
struct VMess {
    // 服务器地址
    add: String,
    // HTTP连接头
    host: String,
    // 客户端ID
    id: String,
    // 网络连接方式
    net: String,
    // 请求路径
    path: String,
    // 端口
    port: String,
    // TAG
    ps: String,
    // Alter Id
    aid: i32,
    // 加密类型
    #[serde(rename = "type")]
    _type: String,
}

/// 解析vmess链接
fn parse_vmess_link(link: &str) -> Option<ComponentV2rayServer> {
    if !link.starts_with("vmess://") {
        return None;
    }

    let link = link.strip_prefix("vmess://").unwrap();
    // log::info!("{}", link);

    let content = base64::prelude::BASE64_STANDARD.decode(link.as_bytes());
    if content.is_err() {
        return None;
    }

    let content = content.unwrap();
    let content = String::from_utf8(content);
    if content.is_err() {
        return None;
    }

    let content = content.unwrap();
    log::info!("{}", content.as_str());

    let vmess = serde_json::from_str::<VMess>(content.as_str());
    if vmess.is_err() {
        return None;
    }

    let vmess = vmess.unwrap();

    let mut server = ComponentV2rayServer::default();
    server.uuid = nanoid!();
    server.tag = vmess.ps;
    server.address = vmess.add;

    let port = vmess.port.parse::<u16>();
    if port.is_err() {
        return None;
    }

    server.port = port.unwrap();
    server.user_id = vmess.id;
    server.alter_id = vmess.aid;
    server.level = 0;
    server.security = vmess._type;
    server.network = match vmess.net.as_str() {
        "tcp" => ComponentV2rayServerNetwork::Tcp,
        "kcp" => ComponentV2rayServerNetwork::Kcp,
        "ws" => ComponentV2rayServerNetwork::WebSocket,
        "http" => ComponentV2rayServerNetwork::Http,
        "quic" => ComponentV2rayServerNetwork::Quic,
        _ => ComponentV2rayServerNetwork::Tcp
    };

    // 目前只支持WS
    if ComponentV2rayServerNetwork::WebSocket == server.network {
        server.websocket_setting.path = vmess.path;
        server.websocket_setting.headers_json_string = format!("{{\"Host\": \"{}\"}}", vmess.host)
    }

    Some(server)
}